package com.shiwei.is.transmission;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * File: null.java
 * Creator: dingpwen
 * Company: shiwei
 * Created on: 2021/3/29 16:46
 * Email: dingpwen@gmail.com
 * Details: TODO
 */
class TestWrite {
    private static final String DEFAULT_FILE_NAME = "test.h264";
    private final Context context;
    private FileOutputStream fos;
    private FileInputStream fis;
    private int curPos;

    public TestWrite(Context context) {
        this.context = context;
        //createOutFilePath();
        createInFilePath();
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public void createOutFilePath() {
        File path = context.getApplicationContext().getExternalFilesDir(null);
        if(!path.exists()) {
            path.mkdirs();
        }
        try {
            fos = new FileOutputStream(path.getAbsolutePath() + "/" + DEFAULT_FILE_NAME);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void createInFilePath() {
        File path = context.getApplicationContext().getExternalFilesDir(null);
        try {
            fis = new FileInputStream(path.getAbsolutePath() + "/" + DEFAULT_FILE_NAME);
            curPos = 0;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void writeFile(byte[] data, int size) {
        try {
            fos.write(data, 0, size);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int readFile(byte[] data, int size) {
        int len = 0;
        try {
            len = fis.read(data, 0, size);
            Log.d("ISApp:TestWrite", "len = " + len);
            curPos += len;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return len;
    }

    public void exit() {
        if(fos != null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
